import { Component, OnInit } from '@angular/core';
import {book} from '../book';
import { pub2sub } from '../pub2subService';

@Component({
  selector: 'app-shell',
  templateUrl: './shell.component.html',
  styleUrls: ['./shell.component.css']
})


export class ShellComponent implements OnInit {
  selectedCategory:number=-1;
  id:number=0;
  categories:category[]=[];
  constructor(private pub2sub :pub2sub) { 
    this.pub2sub = pub2sub;
      this.pub2sub.subscribe('shell','save-new-book',(book:book)=>{
        let category = this.categories.find(category=>category.id==this.selectedCategory);
        console.log(category);
        if(!category) return;
        
        fetch('/app/create/book').finally(()=>{
          book.id=this.id++;
          category?.books.push(book);
          this.pub2sub.notify('book-list','showBooks',category?.books,false);
        })
      })

      pub2sub.subscribe('shell','del-book',(id:number)=>{
        let books = this.categories.find(category=>category.id==this.selectedCategory)?.books;
        let bookIdx = books?.findIndex(book=>book.id===id);
        if(bookIdx===undefined) return;
         books?.splice(bookIdx,1);
        this.pub2sub.notify('book-list','showBooks',books,false);
      })
  }
  
  ngOnInit(): void {
    fetch('/app/query/category').finally(()=>{
      let result = [{id:this.id++,name:'默认',children:[],parent:0,books:[
      ]},{
        id:this.id++,name:'WEB开发从入门到放弃',children:[],parent:0,books:[
          {id:1,name:'WEB入门',author:'叶文洁'},
          {id:2,name:'WEB进阶',author:'云天明'},
          {id:3,name:'WEB精通',author:'程心'},
          {id:4,name:'WEB放弃',author:'维德'},
        ]
      }];
      this.categories = result;
    })
  }
  addCategory(input:HTMLInputElement){
    if(!input.value) return;
    fetch('/app/create/category').finally(()=>{
      let result = {id:this.id++,name:input.value,children:[],parent:0,books:[]};
      this.categories.push(result);
      input.value = "";
    });
  }
  delCategory(id:number){
    fetch('/app/delete/category').finally(()=>{
      let categoryIdx = this.categories.findIndex(category=>category.id==id);

      this.categories.splice(categoryIdx,1);
    });

  }
  
  useThisCategory(id:number){
    this.selectedCategory = id;
    console.log(id);
    let books = this.categories.find(category=>category.id===id)?.books;
    this.pub2sub.notify('book-list','showBooks',books,false);
  }
}

interface category{
  id:number,
  name:string,
  parent:number,
  children:category[],
  books:book[],
}